#include "leaveCommand.h"

QDomDocument LeaveCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result;

    if (this->isAuthorized(doc)) {
        User* me = this->getCurrentUser(doc);
        QDomNodeList roomNodes = doc.elementsByTagName("room");
        if (roomNodes.count() == 1) {
            QString roomName = roomNodes.at(0).toElement().text().trimmed();
            Room* room = DB::getInstance()->findRoom(roomName);
            if (room == NULL) {
                result = "<leave><success>FALSE</success><reason>NO_SUCH_ROOM</reason></leave>";
            } else {
                if (room->isMember(me)) {
                    room->removeUser(me);
                    result = "<leave><success>TRUE</leave>";
                } else {
                   result = "<leave><success>FALSE</success><reason>YOU_ARE_NOT_IN_ROOM</reason></leave>";
                }
            }
        } else {
            result = "<leave><success>FALSE</success><reason>WRONG_XML</reason></leave>";
        }
    } else {
        result = "<leave><success>FALSE</success><reason>NOT_AUTHORIZED</reason></leave>";
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}

